package com.ninjas.module.error.service.impl;

import com.ninjas.module.error.domain.model.User;
import com.ninjas.module.error.mapper.UserMapper;
import com.ninjas.module.error.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private String hashPassword(String password) {
        return DigestUtils.md5Hex(password);
    }

    @Override
    public void registerUser(User user) {
        user.setPassword(hashPassword(user.getPassword()));
        userMapper.insertUser(user);
    }

    @Override
    public boolean authenticateUser(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null) {
            return hashPassword(password).equals(user.getPassword());
        }
        return false;
    }

    @Override
    public boolean isUsernameAvailable(String username) {
        return userMapper.findByUsername(username) == null;
    }

    @Override
    public PageInfo<User> list(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.list();
        return new PageInfo<>(userList);
    }

}
